/**
 * 云开发相关服务封装
 */
export function isCloudReady(): boolean {
  return typeof wx !== "undefined" && !!wx.cloud;
}

/**
 * 上传PDF到云存储并返回 fileID
 */
export async function uploadPdfToCloud(
  localPath: string,
  fileName: string
): Promise<string> {
  if (!isCloudReady()) throw new Error("cloud not initialized");
  const cloudPath = `pdfs/${Date.now()}-${fileName || "unnamed.pdf"}`;
  const res = await wx.cloud.uploadFile({ cloudPath, filePath: localPath });
  return res.fileID;
}

/**
 * 通过 fileID 下载云文件并返回本地临时路径
 */
export async function downloadCloudFile(fileID: string): Promise<string> {
  if (!isCloudReady()) throw new Error("cloud not initialized");
  const res = await wx.cloud.downloadFile({ fileID });
  return res.tempFilePath;
}

/**
 * 去除PDF水印：调用 removewatermark 云函数
 * - 支持默认去水印（居中斜线覆盖）或自定义矩形覆盖
 */
export async function removePdfWatermark(
  fileID: string,
  options?: {
    rects?: Array<{
      x: number;
      y: number;
      width: number;
      height: number;
      rotate?: number;
      normalized?: boolean;
    }>;
    mode?: 'safe' | 'aggressive';
  }
): Promise<string> {
  if (!isCloudReady()) throw new Error("cloud not initialized");
  console.log("[cloud] 调用 removewatermark", { fileID, options });
  const res = await wx.cloud.callFunction({
    name: "removewatermark",
    data: { fileID, coverRects: options?.rects, mode: options?.mode || 'safe' },
  });
  const result = (res && (res as any).result) as any;
  if (!result || result.ok === false) {
    const err =
      result && result.error ? String(result.error) : "remove watermark failed";
    throw new Error(err);
  }
  return String(result.fileID);
}
